# 登录表单
from flask import flash
from flask_login import current_user
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, RadioField, IntegerField, BooleanField
from wtforms.validators import Length, DataRequired, Email, EqualTo, ValidationError

from app import db
from app.models import UserInfo


class LoginForm(FlaskForm):
    username = StringField('用户名', validators=[DataRequired(), Length(min=3, max =10) ])
    password = PasswordField('密码', validators=[DataRequired(), ])
    remember_me = BooleanField('记住我')
    submit = SubmitField('登录')


# 注册表单
class RegisterForm(FlaskForm):
    username = StringField('用户名', validators=[DataRequired(), Length(min=3, max=10)])
    password = PasswordField('密码', validators=[DataRequired(), ])
    sex = RadioField('性别', choices=[('0', '男'), ('1', '女')], validators=[DataRequired(), ])
    age = IntegerField('年龄')
    email = StringField('电子邮箱', validators=[Email()])
    submit = SubmitField('提交')


# 修改密码
class UpdatePwdForm(FlaskForm):
    old_password = PasswordField('旧密码', validators=[DataRequired(), ])
    new_password = PasswordField('新密码', validators=[DataRequired(), ])
    check_password = PasswordField('确认密码', validators=[DataRequired(), EqualTo('new_password', message="两次密码不一致")])
    submit = SubmitField("提交")

    # 校验旧密码
    def validate_old_password(self, field):
        if not current_user.verify_password(field.data):
            raise ValidationError("旧密码错误")

    # 修改密码
    def update_pwd(self):
        user = current_user
        user.password = self.new_password.data
        db.session.add(user)
        try:
            db.session.commit()
            return user
        except Exception as e:
            db.session.rollback()


# 修改邮箱
class UpdateEmail(FlaskForm):
    new_email = StringField('邮箱', validators=[Email(message="请输入邮箱")])
    pwd = PasswordField('密码', validators=[DataRequired(),])
    submit = SubmitField('更新Email')

    # 校验邮箱
    def validate_new_email(self, field):
        if UserInfo.query.filter_by(email=field.data).count() > 0:
            raise ValidationError("邮箱已存在")

    # 校验密码
    def validate_pwd(self, field):
        if not current_user.verify_password(field.data):
            raise ValidationError("密码错误")


# 重置密码
class ResetPassword(FlaskForm):
    email = StringField('电子邮箱', validators=[DataRequired(), Email()])
    submit = SubmitField('重置密码')

    def validate_email(self, field):
        if not UserInfo.query.filter_by(email=field.data).count() > 0:
            raise ValidationError("邮箱不存在")


# 邮箱重置密码
class SendResetPassword(FlaskForm):
    new_password = PasswordField('新密码', validators=[DataRequired(), ])
    check_password = PasswordField('确认密码', validators=[DataRequired(), EqualTo('new_password', message="两次密码不一致")])
    submit = SubmitField("重置密码")

